__author__ = 'Administrator'
from http import client
import re
import threading
import os,time


class BlockDownload(threading.Thread,client.HTTPConnection):
    def __init__(self,url,blockSize,blockIndex):
        threading.Thread.__init__(self)
        urlInfo=self._get_host_path(url)
        self.host=urlInfo[0][0]
        client.HTTPConnection.__init__(self,self.host)
        self.port=80
        self.path=urlInfo[0][1]
        self.fName=urlInfo[0][2]
        self.currentPointer=0
        self.blockSize=blockSize
        self.blockIndex=blockIndex

    def run(self):
        tmpFileName=self.fName + r'_Block_' + str(self.blockIndex)
        f=open(tmpFileName,'ab+')
        hasDownloaded=os.path.getsize(tmpFileName)
        self.currentPointer+=hasDownloaded
        startPosition=self.blockSize*self.blockIndex+hasDownloaded
        endPosition=self.blockSize*(self.blockIndex+1)-1
        self.putrequest('GET',self.path + self.fName)
        self.putheader('Range','bytes=' + str(startPosition) + '-' + str(endPosition))
        self.endheaders()
        res=self.getresponse()
        data=res.read(1024*16)
        while data:
            self.currentPointer+=len(data)
            f.write(data)
            data=res.read(1024*16)
        f.close()

    def _get_host_path(self,url):
        r = re.compile(r'//*(.*?)(/.*/)(.*)')
        match = r.findall(url)
        return match


class SuperDownLoad(client.HTTPConnection):
    def __init__(self,url,thr_count=5):
        urlInfo=self._get_host_path(url)
        self.url=url
        self.host=urlInfo[0][0]
        self.port=80
        self.fName=urlInfo[0][2]
        self.path=urlInfo[0][1] + urlInfo[0][2]
        self.thr_count = thr_count
        super(SuperDownLoad,self).__init__(self.host)

    def start(self):
        self.putrequest('HEAD',self.path)
        self.endheaders()
        totleSize=int(self.getresponse().getheader('Content-Length'))
        blockSize=(totleSize // self.thr_count) + 1
        tasks=[]
        for i in range(self.thr_count):
            task=BlockDownload(self.url,blockSize,i)
            task.start()
            tasks.append(task)
        while self.isActive(tasks):
            progress=sum(item.currentPointer for item in tasks)
            progress='%5.2f %s' % (progress*100/totleSize,'%')
            print(progress)
            time.sleep(3)
        progress=sum(item.currentPointer for item in tasks)
        progress='%5.2f %s' % (progress*100/totleSize,'%')
        print(progress)
        print('File Downloaded!')
        bigF=open(self.fName,'ab+')
        for i in range(self.thr_count):
            littleF=open(self.fName + '_Block_' + str(i),'rb+')
            data=littleF.read(1024*1024)
            while data:
                bigF.write(data)
                data=littleF.read(1024*1024)
            littleF.close()
        bigF.close()
        self.reMove()

    def _get_host_path(self,url):
        r = re.compile(r'//(.*?)(/.*/)(.*)')
        match = r.findall(url)
        return match

    def isActive(self,tasks):
        isActive=False
        for task in tasks:
            if task.is_alive():
                isActive=True
        return isActive

    def reMove(self):
        for i in range(self.thr_count):
            os.remove(self.fName + '_Block_' + str(i))

t=SuperDownLoad('http://21.44.44.181/internet/fgunrc.rar',3)
t.start()